<template>
    <div class="map_container">
      <div id="main_map2d" style="width: 100%; height: 100%; overflow: hidden"></div>
      <!-- 格网 -->
    <div v-if="isMobile" style="position: absolute; left: calc(12px); bottom: 106px; z-index: 9; display: grid;">
      <el-button style="margin: 8px auto" @click="_checkGridLayer('layer')" class="grid_buttons"
    :style="showGrid.layer ? { background: 'rgb(45, 140, 255)', color: 'white'} : { background: '#f5f7fa' }">
        <span style="font-size: 16px; margin-right: 4px" class="esri-icon-basemap">
        </span>
        <span style="font-size: 16px" :style="showGrid.layer ? { color: 'white' } : {}">
          地理格网</span>
      </el-button>
      <el-button style="margin: 8px auto" @click="_checkGridLayer('label')" class="grid_buttons"
    :style="showGrid.label ? { background: 'rgb(45, 140, 255)', color: 'white'} : { background: '#f5f7fa'} ">
        <span style="font-size: 16px; margin-right: 4px" class="esri-icon-labels">
        </span>
        <span style="font-size: 16px" :style="showGrid.label ? { color: 'white' } : {}">格网编码</span>
      </el-button>
    </div>
    </div>
  </template>
  
  <script>
  import QRCode from "qrcode";
  
  import esriConfig from "@arcgis/core/config.js";
  import Map from "@arcgis/core/Map";
  import Basemap from "@arcgis/core/Basemap";
  import BasemapToggle from "@arcgis/core/widgets/BasemapToggle";
  import ScaleBar from "@arcgis/core/widgets/ScaleBar";
  import MapView from "@arcgis/core/views/MapView";
  import SceneView from "@arcgis/core/views/SceneView";
  import Graphic from "@arcgis/core/Graphic";
  import Point from "@arcgis/core/geometry/Point";
  import Extent from "@arcgis/core/geometry/Extent";
  import TileLayer from "@arcgis/core/layers/TileLayer";
  import TileInfo from "@arcgis/core/layers/support/TileInfo";
  import MapImageLayer from "@arcgis/core/layers/MapImageLayer";
  import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
  import WebTileLayer from "@arcgis/core/layers/WebTileLayer";
  import WMTSLayer from "@arcgis/core/layers/WMTSLayer";
  import VectorTileLayer from "@arcgis/core/layers/VectorTileLayer";
  import * as reactiveUtils from "@arcgis/core/core/reactiveUtils";
  import FeatureFilter from "@arcgis/core/layers/support/FeatureFilter";
  import * as geometryEngine from "@arcgis/core/geometry/geometryEngine";
  import CustomContent from "@arcgis/core/popup/content/CustomContent";
  
  export default {
    name: "SpatialEncodingMap",
    data() {
      return {
        isMobile: false,

        dynamicCommand: null,
        dynamicLeftComponent: null,
        dynamicRightComponent: null,
        dynamicEntireComponent: null,
        dynamicIndieComponents: [],
        fullscreenStatus: false,
        assetsPath: "https://nfzjszlb.jst.zj.gov.cn/ZheJiangSpatialEncoding",
        houses_Url: "https://nfzjszlb.jst.zj.gov.cn/tyzcpt/api/gisrest/arcgis/featurelayer/fwdlbm_zjscz",
        houses_Url2: "https://nfzjszlb.jst.zj.gov.cn/api/gisrest/arcgis/featurelayer/fwdlbm_zjsnc",
        addressInterfaceUrl:
          "https://restapi.amap.com/v3/place/text?key=d22ca1a1c8d39ea07fa038b221ea6461&extensions=all&offset=50&page=1",
        showSearchResult: true,
        searchValue: "",
        selectConditionIndex: 0,
        selectConditionCollection: [
          {
            name: "all",
            param: ["jzmc", "address", "fwdlbm"],
            placeholder: "输入建筑名称、地名地址、房屋统一码",
          },
          { name: "建筑名称", param: "jzmc", placeholder: "建筑名称" },
          { name: "建筑地址", param: "address", placeholder: "建筑地址" },
          // { name: "房屋编号", param: "fwbh", placeholder: "房屋编号" },
          {
            name: "房屋统一码",
            param: "fwdlbm",
            placeholder: "房屋统一码",
          },
        ],
        searchResult: [],
        searchResultPage: 1,
        showGrid: {
          layer: true,
          label: false,
        },
        gridLevel: -1,
        showPanel: true,
  
        divisionsOptions: [],
        selectedDivision: null,
  
        checkingFeatureInfo: null,
        selectedErrorType: "属性信息错误"
      };
    },
    created() {
      const isMobile = navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      );
      this.isMobile = isMobile
      esriConfig.assetsPath = "https://nfzjszlb.jst.zj.gov.cn/tyzcpt/esriAssets/esriAssets";
    },
    methods: {
      // 初始化地图 异步
      initMap(mapViewType) {
        const self = this;
        return new Promise((resolve, reject) => {
          const active3D = mapViewType === "3d" ? true : false;
          self.dynamicCommand = null;
          self.dynamicLeftComponent = null;
          self.dynamicRightComponent = null;
          self.dynamicEntireComponent = null;
          self.dynamicIndieComponents = [];
          if (self.extentWatcher) {
            self.extentWatcher.remove();
          }
          if (self.triggerActionHandler) {
            self.triggerActionHandler.remove();
          }
          if (self.scaleBar) {
            self.scaleBar.destroy();
          }
          if (self.mapView) {
            self.mapView.ui.empty();
          }
          if (!active3D) {
            const map = new Map({
              basemap:
                self.initBaseMapType === "影像地图"
                  ? self.satelliteBaseMaps
                  : self.othersBaseMaps,
            });
            self.mapView = new MapView({
              container: "main_map" + mapViewType,
              map: map,
              extent: self.initExtent.expand(1),
              spatialReference: self.initExtent.spatialReference,
              constraints: {
                rotationEnabled: false,
                minScale: 6000000,
              },
            });
          } else {
            const map3d = new Map({
              basemap:
                self.initBaseMapType === "影像地图"
                  ? self.satelliteBaseMaps
                  : self.othersBaseMaps,
              ground: {
                surfaceColor: "rgba(255, 255, 255, 0)",
                navigationConstraint: {
                  // type: "stay-above"
                  type: "none",
                },
              },
            });
            self.mapView = new SceneView({
              container: "main_map" + mapViewType,
              map: map3d,
              qualityProfile: "medium",
              // viewingMode: "local",
              extent: self.initExtent.expand(1.2),
              // clippingArea: self.initExtent.expand(1.2),
              environment: {
                starsEnabled: true,
                atmosphere: {
                  quality: "high",
                },
                lighting: {
                  // date: Date.now(),
                  directShadowsEnabled: false,
                },
              },
              spatialReference: self.initExtent.spatialReference,
            });
          }
          self.mapView.ui.empty("top-left");
          self.mapView.ui.remove("attribution");
          const basemapToggle = new BasemapToggle({
            view: self.mapView,
            nextBasemap:
              self.initBaseMapType === "影像地图"
                ? self.othersBaseMaps
                : self.satelliteBaseMaps,
            visibleElements: {
              title: true,
            },
          });
          self.mapView.ui.add(basemapToggle, {
            position: "bottom-right",
          });
          self.scaleBar = new ScaleBar({
            // id: "scaleBar",
            // container: 'scaleBarDiv',
            view: self.mapView,
            unit: "metric",
          });
          self.mapView.ui.add(self.scaleBar, {
            position: "bottom-left",
          });
  
          self.mapView.popup = {
            highlightEnabled: true,
            // updateLocationEnabled: true,
            dockEnabled: true,
            dockOptions: {
              buttonEnabled: false,
              breakpoint: false,
              position: "bottom-right",
            },
          };
          let nowExtent = null;
          self.extentWatcher = reactiveUtils.watch(
            () => self.mapView.stationary,
            (e) => {
              if (e) {
                // console.info(`scale：${self.mapView.scale}`);
                self.$emit("scaleChanging", {
                  extent: self.mapView.extent,
                  scale: self.mapView.scale,
                });
                if (
                  nowExtent === null ||
                  (nowExtent && nowExtent.xmax !== self.mapView.extent.xmax)
                ) {
                  nowExtent = self.mapView.extent;
                  self._createGridLayer();
                }
              }
            }
          );
          self.triggerActionHandler = self.mapView.popup.viewModel.on(
            "trigger-action",
            function (event) {
              self.mapView.popup.dockEnabled = false;
              const selectingFeature =
                self.mapView.popup.viewModel.selectedFeature;
              console.info("selectingFeature:", selectingFeature);
              switch (event.action.id) {
                default:
                  break;
              }
            }
          );
  
          self.selectedGridGraphics = [];
  
          // 格网
          self.moveHandler = self.mapView.on("pointer-move", (e) => {
            self.mapView.hitTest(e).then((hitResponse) => {
              const checkGridLayerid = "gridLayer";
              let gotGrid = false;
              if (hitResponse.results.length) {
                const getGraphic = hitResponse.results.find((hitResult) => {
                  return (
                    hitResult.graphic.layer &&
                    hitResult.graphic.layer.id === checkGridLayerid
                  );
                });
                if (getGraphic) {
                  gotGrid = true;
                }
              }
              self.mapView.cursor = gotGrid ? "pointer" : "default";
            });
          });
  
          self.popupVisibleWatcher = reactiveUtils.watch(
            () => self.mapView.popup.visible,
            (e) => {
              if (!e) {
                if (self.identifyFeatures) {
                  self.mapView.graphics.removeMany(self.identifyFeatures);
                  self.identifyFeatures = null;
                }
              }
            }
          );
          self.selectedFeatureHandler = self.mapView.popup.watch(
            "selectedFeature",
            (graphic) => {
              console.info("selectedFeature:", graphic)
              if (graphic && graphic.geometry) {
                const cp = graphic.geometry.centroid ? graphic.geometry.centroid : graphic.geometry
                console.info("几何中心坐标：", cp)
                console.info("编码：", self._getGirdCode(cp.x, cp.y, 3))
              }
            })
  
          self.triggerActionHandler = self.mapView.popup.viewModel.on("trigger-action",
            function (event) {
              // self.mapView.popup.dockEnabled = false;
              const selectingFeature = self.mapView.popup.viewModel.selectedFeature;
              switch (event.action.id) {
                case "纠错":
                  self.checkingFeatureInfo = {
                    name: selectingFeature.attributes.jzmc,
                    type: ""
                  }
                  break;
                default:
                  break;
              }
            }
          );
  
          self._initLayers();
  
          resolve();
        });
      },
      _initLayers() {
        const self = this;
        self.uploadingFeatures = [];
        self.censusLayerFieldInfos = [
          // { alias: "房屋编号", name: "fwbh" },
          { alias: "建筑名称", name: "jzmc" },
          { alias: "地址", name: "address" },
          { alias: "房屋统一码", name: "fwdlbm" },
          { alias: "单位/小区名称", name: "mc" },
          { alias: "设区市", name: "city" },
          { alias: "区（市、县）", name: "xmc" },
          { alias: "乡镇/街道", name: "town" },
          { alias: "建成年份", name: "build_time" },
        ];
        self.censusLayerFieldInfos2 = [
          // { alias: "房屋编号", name: "fwbh" },
          { alias: "建筑名称", name: "jzmc" },
          { alias: "地址", name: "address" },
          { alias: "房屋统一码", name: "fwdlbm" },
          { alias: "设区市", name: "city" },
          { alias: "区（市、县）", name: "xmc" },
          { alias: "乡镇/街道", name: "town" },
          { alias: "建成年份", name: "build_time" },
        ];
        self.censusLayerOutFields = self.censusLayerFieldInfos.map(
          (configField) => {
            return configField.name;
          }
        );
        self.censusLayerOutFields2 = self.censusLayerFieldInfos2.map(
          (configField) => {
            return configField.name;
          }
        );
        let renderer = {
          type: "unique-value",
          // field: "fwdlbm",
          valueExpression: "DefaultValue($feature.fwdlbm, '未赋码')",
          defaultSymbol: {
            type: "simple-fill",
            style: "solid",
            color: "rgba(0,0,0,0)",
            outline: {
              color: "limegreen",
              width: 1.5,
            },
          },
          uniqueValueInfos: [
            {
              value: "未赋码",
              symbol: {
                type: "simple-fill",
                style: "solid",
                color: "rgba(0,0,0,0)",
                outline: {
                  color: "red",
                  width: 1.5,
                },
              },
            },
            {
              value: "已赋码",
              symbol: {
                type: "simple-fill",
                style: "solid",
                color: "rgba(0,0,0, 0)",
                outline: {
                  color: "limegreen",
                  width: 1.5,
                },
              },
            },
          ],
        };
        self.censusLayer = new FeatureLayer({
          id: "censusLayer",
          title: "城镇灾普图层",
          outFields: self.censusLayerOutFields,
          url: self.houses_Url,
          // renderer: renderer,
          minScale: 14000,
          visible: true,
        });
        self.mapView.map.add(self.censusLayer);
        self.mapView
          .whenLayerView(self.censusLayer)
          .then(function (censusLayerView) {
            const popupFields = self.censusLayerFieldInfos; //censusLayerView.layer.fields;
            // self.censusLayerFieldInfos = censusLayerView.layer.fields;
            if (popupFields) {
              const fieldInfos = [];
              popupFields.forEach((field) => {
                fieldInfos.push({
                  fieldName: field.name,
                  label: field.alias,
                });
              });
              let qrcodeElement = new CustomContent({
                outFields: ["*"],
                creator: async (event) => {
                  const u = `${self.assetsPath}/#/SpatialEncodingQRPage?fwbh=${event.graphic.attributes.fwbh}`;
                  const imgurl = await QRCode.toDataURL(u);
                  const div = document.createElement("div");
                  div.style.width = "100%";
                  div.style.height = "160px";
                  div.style.lineHeight = "160px";
                  div.style.display = "inline-flex";
                  const img = document.createElement("img");
                  img.setAttribute("src", imgurl);
                  img.style.margin = "0px auto";
                  img.style.height = "160px";
                  img.style.width = "160px";
                  div.appendChild(img);
                  return div;
                },
              });
              let buttonElement = new CustomContent({
                outFields: ["*"],
                creator: (event) => {
                  const div = document.createElement("div");
                  div.style.width = "100%";
                  div.style.height = "36px";
                  div.style.lineHeight = "36px";
                  div.style.display = "inline-flex";
                  const button = document.createElement("button");
                  button.classList.add("el-button");
                  // button.classList.add("el-button--small");
                  button.classList.add("el-button--primary");
                  button.classList.add("pickFWKJMButtons");
                  button.classList.add("pickFWKJMButtons_flash");
                  button.style.margin = "2px auto";
                  button.style.padding = "4px 8px";
                  button.setAttribute(
                    "data-clipboard-text",
                    event.graphic.attributes.fwdlbm
                  );
                  button.setAttribute("title", "复制房屋统一码");
                  const t = document.createTextNode("复制房屋统一码");
                  button.appendChild(t);
                  div.appendChild(button);
                  return div;
                },
              });
              self.censusLayer.popupTemplate = {
                title: "城镇房屋属性",
                content: [
                  qrcodeElement,
                  buttonElement,
                  {
                    type: "fields",
                    fieldInfos: fieldInfos,
                  },
                ],
                actions: [{
                  title: "纠错",
                  id: "纠错",
                  className: "esri-icon-notice-triangle",
                }],
                outFields: self.censusLayerOutFields,
              };
            }
            if (
              self.divisionGeometry &&
              self.divisionGeometry.type === "polygon" &&
              self.cityCode
            ) {
              censusLayerView.filter = new FeatureFilter({
                geometry: self.divisionGeometry,
                spatialRelationship: "intersects",
              });
            }
          });
        self.censusLayer2 = new FeatureLayer({
          id: "censusLayer2",
          title: "农村灾普图层",
          outFields: self.censusLayerOutFields2,
          url: self.houses_Url2,
          // renderer: renderer,
          minScale: 14000,
          visible: true,
        });
        self.mapView.map.add(self.censusLayer2);
        self.mapView
          .whenLayerView(self.censusLayer2)
          .then(function (censusLayerView) {
            const popupFields = self.censusLayerFieldInfos2; //censusLayerView.layer.fields;
            // self.censusLayerFieldInfos = censusLayerView.layer.fields;
            if (popupFields) {
              const fieldInfos = [];
              popupFields.forEach((field) => {
                fieldInfos.push({
                  fieldName: field.name,
                  label: field.alias,
                });
              });
              let qrcodeElement = new CustomContent({
                outFields: ["*"],
                creator: async (event) => {
                  const u = `${self.assetsPath}/#/SpatialEncodingQRPage?fwbh=${event.graphic.attributes.fwbh}`;
                  const imgurl = await QRCode.toDataURL(u);
                  const div = document.createElement("div");
                  div.style.width = "100%";
                  div.style.height = "160px";
                  div.style.lineHeight = "160px";
                  div.style.display = "inline-flex";
                  const img = document.createElement("img");
                  img.setAttribute("src", imgurl);
                  img.style.margin = "0px auto";
                  img.style.height = "160px";
                  img.style.width = "160px";
                  div.appendChild(img);
                  return div;
                },
              });
              let buttonElement = new CustomContent({
                outFields: ["*"],
                creator: (event) => {
                  const div = document.createElement("div");
                  div.style.width = "100%";
                  div.style.height = "36px";
                  div.style.lineHeight = "36px";
                  div.style.display = "inline-flex";
                  const button = document.createElement("button");
                  button.classList.add("el-button");
                  // button.classList.add("el-button--small");
                  button.classList.add("el-button--primary");
                  button.classList.add("pickFWKJMButtons");
                  button.classList.add("pickFWKJMButtons_flash");
                  button.style.margin = "2px auto";
                  button.style.padding = "4px 8px";
                  button.setAttribute(
                    "data-clipboard-text",
                    event.graphic.attributes.fwdlbm
                  );
                  button.setAttribute("title", "复制房屋统一码");
                  const t = document.createTextNode("复制房屋统一码");
                  button.appendChild(t);
                  div.appendChild(button);
                  return div;
                },
              });
              self.censusLayer2.popupTemplate = {
                title: "农村房屋属性",
                content: [
                  qrcodeElement,
                  buttonElement,
                  {
                    type: "fields",
                    fieldInfos: fieldInfos,
                  },
                ],
                actions: [{
                  title: "纠错",
                  id: "纠错",
                  className: "esri-icon-notice-triangle",
                }],
                outFields: self.censusLayerOutFields2,
              };
            }
            if (
              self.divisionGeometry &&
              self.divisionGeometry.type === "polygon" &&
              self.cityCode
            ) {
              censusLayerView.filter = new FeatureFilter({
                geometry: self.divisionGeometry,
                spatialRelationship: "intersects",
              });
            }
          });
      },
      _createGridLayer() {
        if (!this.gridLevel) {
          this.gridLevel = -1;
        }
        if (this.gridLayer) {
          this.mapView.map.remove(this.gridLayer);
        }
        const zoom = Math.floor(this.mapView.zoom);
        if (zoom <= 11) {
          // 十分格网
          this.gridLevel = 1;
        } else if (zoom <= 14) {
          // 分格网
          this.gridLevel = 2;
        } else if (zoom <= 16) {
          // 十秒格网
          this.gridLevel = 3;
        } else {
          // 三秒格网
          this.gridLevel = 3;
          // this.gridLevel = 4;
        }
  
        const showGrid = this.showGrid;
  
        const gridsSymbol = {
          type: "simple-fill",
          style: "solid",
          color: [170, 90, 255, 0.4],
          outline: {
            color: [0, 0, 240, 0.6],
            width: 1,
          },
        };
        const labelsSymbol = {
          type: "text",
          color: "orange",
          haloColor: "rgb(100, 100, 100)",
          haloSize: "1px",
          font: {
            family: "Microsoft-YaHei",
            size: 10,
          },
          // text: `${"杭州市"}\n ${233}`,
          // horizontalAlignment: "center",
          // verticalAlignment: "middle",
        };
        const grids = [];
        let noeExent = this.mapView.extent.clone();
        noeExent = noeExent.expand(2);
        let xmin = 118;
        let xmax = 123;
        let ymin = 27;
        let ymax = 32;
        const section =
          0.0002777777778 *
          (this.gridLevel === 1
            ? 600
            : this.gridLevel === 2
              ? 60
              : this.gridLevel === 3
                ? 10
                : 3);
        let count = 0;
        for (let i = xmin; i < xmax; i += section) {
          if (
            this.gridLevel === 1 ||
            (this.gridLevel !== 1 && i >= noeExent.xmin && i <= noeExent.xmax)
          ) {
            for (let j = ymin; j < ymax; j += section) {
              if (
                this.gridLevel === 1 ||
                (this.gridLevel !== 1 && j >= noeExent.ymin && j <= noeExent.ymax)
              ) {
                count++;
                const polygon = new Graphic({
                  attributes: {
                    objectId: count,
                    code: this._getGirdCode(i, j, this.gridLevel, false),
                  },
                  geometry: {
                    type: "polygon",
                    rings: [
                      [
                        [i, j + section],
                        [i + section, j + section],
                        [i + section, j],
                        [i, j],
                        [i, j + section],
                      ],
                    ],
                    spatialReference: this.mapView.spatialReference,
                  },
                });
                grids.push(polygon);
              }
            }
          }
        }
        // console.info(`格网数：${count}`);
  
        this.gridLayer = new FeatureLayer({
          id: "gridLayer_" + this.gridLevel,
          labelingInfo: [
            {
              symbol: labelsSymbol,
              labelExpressionInfo: {
                expression: "$feature.code",
              },
            },
          ],
          source: grids,
          objectIdField: "objectId",
          fields: [
            {
              name: "objectId",
              type: "oid",
            },
            {
              name: "code",
              type: "string",
            },
          ],
          renderer: {
            type: "simple",
            symbol: gridsSymbol,
          },
          geometryType: "polygon",
          spatialReference: this.mapView.spatialReference,
          visible: showGrid["layer"],
          labelsVisible: showGrid["label"],
        });
        this.mapView.map.add(this.gridLayer);
      },
      _checkGridLayer(type) {
        const showGrid = this.showGrid;
        showGrid[type] = !showGrid[type];
        this.showGrid = showGrid;
        if (this.gridLayer) {
          this.gridLayer.visible = showGrid["layer"];
          this.gridLayer.labelsVisible = showGrid["label"];
        }
      },
      _getGirdCode(x, y, level, setType) {
        function formatDegree(value) {
          value = Math.abs(value);
          let v1 = Math.floor(value); //度
          let v2 = Math.floor((value - v1) * 60); //分
          let v3 = Math.round(((value - v1) * 3600) % 60); //秒
          if (v3 === 60) {
            v2++;
            v3 = 0;
          }
          if (v2 === 60) {
            v1++;
            v2 = 0;
          }
          return v1 + "°" + v2 + "'" + v3 + '"';
        }
        let newX = formatDegree(x);
        let newY = formatDegree(y);
        newX = newX
          .replace("°", "-")
          .replace("'", "-")
          .replace('"', "")
          .split("-");
        newY = newY
          .replace("°", "-")
          .replace("'", "-")
          .replace('"', "")
          .split("-");
        if (level === 1) {
          //十分
          newX[1] = Math.floor(Number(newX[1]) / 10);
          newY[1] = Math.floor(Number(newY[1]) / 10);
          let code = `${setType ? "NE10M" : ""}${newY[0]}${newX[0]}0${newY[1]}0${newX[1]
            }`;
          return code;
        } else if (level === 2) {
          // 分
          newX[1] = Number(newX[1]);
          newY[1] = Number(newY[1]);
          if (Math.floor(newX[1] / 10) < 1) {
            newX[1] = `0${newX[1]}`;
          }
          if (Math.floor(newY[1] / 10) < 1) {
            newY[1] = `0${newY[1]}`;
          }
          let code = `${setType ? "NE01M" : ""}${newY[0]}${newX[0]}${newY[1]}${newX[1]
            }`;
          return code;
        } else if (level === 3) {
          // 十秒
          newX[1] = Number(newX[1] * 6) + Math.floor(Number(newX[2]) / 10);
          newY[1] = Number(newY[1] * 6) + Math.floor(Number(newY[2]) / 10);
          if (Math.floor(newX[1] / 10) < 1) {
            newX[1] = `000${newX[1]}`;
          } else if (Math.floor(newX[1] / 100) < 1) {
            newX[1] = `00${newX[1]}`;
          } else if (Math.floor(newX[1] / 1000) < 1) {
            newX[1] = `0${newX[1]}`;
          }
          if (Math.floor(newY[1] / 10) < 1) {
            newY[1] = `000${newY[1]}`;
          } else if (Math.floor(newY[1] / 100) < 1) {
            newY[1] = `00${newY[1]}`;
          } else if (Math.floor(newY[1] / 1000) < 1) {
            newY[1] = `0${newY[1]}`;
          }
          let code = `${setType ? "NE10S" : ""}${newY[0]}${newX[0]}${newY[1]}${newX[1]
            }`;
          return code;
        } else {
          // 三秒
          newX[1] = Number(newX[1] * 20) + Math.floor(Number(newX[2]) / 3);
          newY[1] = Number(newY[1] * 20) + Math.floor(Number(newY[2]) / 3);
          if (Math.floor(newX[1] / 10) < 1) {
            newX[1] = `000${newX[1]}`;
          } else if (Math.floor(newX[1] / 100) < 1) {
            newX[1] = `00${newX[1]}`;
          } else if (Math.floor(newX[1] / 1000) < 1) {
            newX[1] = `0${newX[1]}`;
          }
          if (Math.floor(newY[1] / 10) < 1) {
            newY[1] = `000${newY[1]}`;
          } else if (Math.floor(newY[1] / 100) < 1) {
            newY[1] = `00${newY[1]}`;
          } else if (Math.floor(newY[1] / 1000) < 1) {
            newY[1] = `0${newY[1]}`;
          }
          let code = `${setType ? "NE03S" : ""}${newY[0]}${newX[0]}${newY[1]}${newX[1]
            }`;
          return code;
        }
      },
      setExtent(extent) {
        this.mapView.extent = extent;
      },
      flashFeatures(geometries, mapView, options = { customSymbol: null, customZoom: null, isRemain: false }) {
    const self = this;
    return new Promise((resolve, reject) => {
      const HighlightSymbol = {
        "2d": {
          point: {
            type: "simple-marker",
            style: "circle",
            color: '#00ffff',
            size: 18,
            outline: {
              color: [30, 200, 255, 1],
              width: 1,
            },
          },
          polyline: {
            type: "simple-line",
            style: "solid",
            color: "#00ffff",
            width: 3,
          },
          polygon: {
            type: "simple-fill",
            style: "solid",
            color: [0, 255, 255, 0.2],
            outline: {
              color: [30, 200, 255, 1],
              width: 2,
            },
          }
    
        },
        "3d": {
          point: {
            type: "point-3d",
            symbolLayers: [{
              type: "icon",
              size: 16,
              resource: {
                primitive: "circle"
              },
              material: {
                color: '#00ffff'
              },
              outline: {
                color: [30, 200, 255, 1],
                size: 1
              }
            }]
          },
          polyline: {
            type: "line-3d",
            symbolLayers: [{
              type: "line",
              size: 3,
              material: {
                color: "#00ffff"
              },
              cap: "round",
              join: "round"
            }]
          },
          polygon: {
            type: "polygon-3d",
            symbolLayers: [{
              type: "fill",
              material: {
                color: [0, 255, 255, 0.2]
              },
              outline: {
                color: [30, 200, 255, 1],
                size: 3
              }
            }],
          }
        }
      }
      let highlightSymbol = Object.assign({}, HighlightSymbol[mapView.type])
      if (options.highlightSymbol) {
        highlightSymbol = options.highlightSymbol
      }
      const graphics = [];
      geometries.forEach((geo) => {
        const graphic = new Graphic({
          symbol: highlightSymbol[geo.type],
          geometry: geo,
        });
        graphics.push(graphic);
      });
      const goToParameters = options.customZoom
        ? {
          target: graphics,
          zoom: options.customZoom,
        }
        : graphics;
      let flashTimes = 0;
      const falshTask = setInterval(() => {
        flashTimes++;
        mapView.graphics.addMany(graphics);
        if (flashTimes >= 3) {
          clearInterval(falshTask);
        }
        setTimeout(() => {
          mapView.graphics.removeMany(graphics);
          if (flashTimes >= 3 && options.isRemain) {
            mapView.graphics.addMany(graphics);
          }
        }, 700);
      }, 1400);
      mapView
        .goTo(goToParameters, {
          easing: "ease-out",
          duration: 1000,
        })
        .then((r) => {
          resolve();
        })
        .catch((e) => {
          resolve();
        });
    });
  }
    },
    mounted() {
      const self = this;
      self.initExtent = new Extent(
        {
          xmax: 124.6285984894987,
          xmin: 116.20054384066296,
          ymax: 31.275309813616722,
          ymin: 27.138100695633554,
          spatialReference: {
            wkid: 4490
          }
        }
      );
      const configBaseMaps = [
        {
          title: '惠州市遥感影像：注记',
          class: '影像地图',
          type: 'web-tile',
          applyCustomTile: 'TileInfoTMap',
          minScale: 1200,
          order: 0,
          urlTemplate: 'https://yztbh.jst.zj.gov.cn:9520/img_lab?token=d4cd38ad-69ab-4726-84bf-451c1c9a1146' + '&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&STYLE=default&TILEMATRIXSET=esritilematirx&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&FORMAT=image%2Fjpgpng',
        },
        {
          title: '惠州市遥感影像',
          class: '影像地图',
          type: 'web-tile',
          applyCustomTile: 'TileInfoTMap',
          minScale: 1200,
          order: 1,
          urlTemplate: 'https://yztbh.jst.zj.gov.cn:9520/imgmap?token=d4cd38ad-69ab-4726-84bf-451c1c9a1146' + '&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&STYLE=default&TILEMATRIXSET=esritilematirx&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&FORMAT=image%2Fjpgpng',
        },
        {
          title: '惠州市电子地图：注记',
          class: '电子地图',
          type: 'web-tile',
          applyCustomTile: 'TileInfoTMap',
          minScale: 1200,
          order: 2,
          urlTemplate: 'https://yztbh.jst.zj.gov.cn:9520/emap_lab?token=d4cd38ad-69ab-4726-84bf-451c1c9a1146' + '&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&STYLE=default&TILEMATRIXSET=esritilematirx&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&FORMAT=image%2Fjpgpng',
        },
        {
          title: '惠州市电子地图',
          class: '电子地图',
          type: 'web-tile',
          applyCustomTile: 'TileInfoTMap',
          minScale: 1200,
          order: 3,
          urlTemplate: 'https://yztbh.jst.zj.gov.cn:9520/emap?token=d4cd38ad-69ab-4726-84bf-451c1c9a1146' + '&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&STYLE=default&TILEMATRIXSET=esritilematirx&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&FORMAT=image%2Fjpgpng',
        },
        // 国家天地图
        {
          title: '国家天地图影像地图：注记',
          class: '影像地图',
          type: 'web-tile',
          applyCustomTile: 'TileInfoTMap',
          maxScale: 1200,
          order: 4,
          subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
          urlTemplate: 'https://{subDomain}.tianditu.gov.cn/cia_c/wmts?layer=cia&style=default&tilematrixset=c&service=wmts&request=gettile&version=1.0.0&format=tiles&tilematrix={level}&tilecol={col}&tilerow={row}&tk=26e04a33ff17a2107699002df53e5063'
        },
        {
          title: '国家天地图影像地图',
          class: '影像地图',
          type: 'web-tile',
          applyCustomTile: 'TileInfoTMap',
          maxScale: 1200,
          order: 5,
          subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
          urlTemplate: 'https://{subDomain}.tianditu.gov.cn/img_c/wmts?layer=img&style=default&tilematrixset=c&service=wmts&request=gettile&version=1.0.0&format=tiles&tilematrix={level}&tilecol={col}&tilerow={row}&tk=26e04a33ff17a2107699002df53e5063'
        },
        {
          title: '国家天地图电子地图：注记',
          class: '电子地图',
          type: 'web-tile',
          applyCustomTile: 'TileInfoTMap',
          maxScale: 1200,
          order: 6,
          subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
          urlTemplate: 'https://{subDomain}.tianditu.gov.cn/cva_c/wmts?layer=cva&style=default&tilematrixset=c&service=wmts&request=gettile&version=1.0.0&format=tiles&tilematrix={level}&tilecol={col}&tilerow={row}&tk=26e04a33ff17a2107699002df53e5063'
        },
        {
          title: '国家天地图电子地图',
          class: '电子地图',
          type: 'web-tile',
          //effect: "brightness(0.9)",
          applyCustomTile: 'TileInfoTMap',
          maxScale: 1200,
          order: 7,
          subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
          urlTemplate: 'https://{subDomain}.tianditu.gov.cn/vec_c/wmts?layer=vec&style=default&tilematrixset=c&service=wmts&request=gettile&version=1.0.0&format=tiles&tilematrix={level}&tilecol={col}&tilerow={row}&tk=26e04a33ff17a2107699002df53e5063'
        }
      ]
      configBaseMaps.sort((a, b) => {
        return a.order - b.order;
      });
      self.initBaseMapType = configBaseMaps[0]
        ? configBaseMaps[0].class
        : "电子地图";
      configBaseMaps.sort((a, b) => {
        return b.order - a.order;
      });
  
      const othersBaseLayers = [];
      const satelliteBaseLayers = [];
      const TileInfoTMap = {
        "rows": 256,
        "cols": 256,
        "compressionQuality": 0,
        "origin": {
          "x": -180,
          "y": 90
        },
        "spatialReference": {
          "wkid": 4490
        },
        "lods": [{
          "level": 0,
          "resolution": 1.40625002621094,
          "scale": 590995197.148203
        },
        {
          "level": 1,
          "resolution": 0.703125013105469,
          "scale": 295497598.574101
        },
        {
          "level": 2,
          "resolution": 0.351562506552734,
          "scale": 147748799.287051
        },
        {
          "level": 3,
          "resolution": 0.175781253276367,
          "scale": 73874399.6435253
        },
        {
          "level": 4,
          "resolution": 0.0878906266381836,
          "scale": 36937199.8217627
        },
        {
          "level": 5,
          "resolution": 0.0439453133190918,
          "scale": 18468599.9108813
        },
        {
          "level": 6,
          "resolution": 0.0219726566595459,
          "scale": 9234299.95544067
        },
        {
          "level": 7,
          "resolution": 0.0109863283297729,
          "scale": 4617149.97772033
        },
        {
          "level": 8,
          "resolution": 0.00549316416488647,
          "scale": 2308574.98886017
        },
        {
          "level": 9,
          "resolution": 0.00274658208244324,
          "scale": 1154287.49443008
        },
        {
          "level": 10,
          "resolution": 0.00137329104122162,
          "scale": 577143.747215042
        },
        {
          "level": 11,
          "resolution": 0.000686645520610809,
          "scale": 288571.873607521
        },
        {
          "level": 12,
          "resolution": 0.000343322760305405,
          "scale": 144285.93680376
        },
        {
          "level": 13,
          "resolution": 0.000171661380152702,
          "scale": 72142.9684018802
        },
        {
          "level": 14,
          "resolution": 8.58306900763512E-05,
          "scale": 36071.4842009401
        },
        {
          "level": 15,
          "resolution": 4.29153450381756E-05,
          "scale": 18035.7421004701
        },
        {
          "level": 16,
          "resolution": 2.14576725190878E-05,
          "scale": 9017.87105023503
        },
        {
          "level": 17,
          "resolution": 1.07288362595439E-05,
          "scale": 4508.93552511751
        },
        {
          "level": 18,
          "resolution": 5.36441812977195E-06,
          "scale": 2254.46776255876
        },
        {
          "level": 19,
          "resolution": 2.68220906488597E-06,
          "scale": 1127.23388127938
        },
        {
          "level": 20,
          "resolution": 1.34110453244299E-06,
          "scale": 563.616940639689
        }
        ]
      }
      configBaseMaps.forEach((m, index) => {
        let initLayer = null;
        let urlTemplate = "";
        switch (m.type) {
          case "tile":
            if (m.applyCustomTile) {
              if (TileInfoTMap) {
                initLayer = new TileLayer({
                  url: m.url,
                  title: m.title,
                  tileInfo: new TileInfo(TileInfoTMap
                  ),
                });
              } else {
                console.error(
                  "底图 [" +
                  m.title +
                  "] 所声明自定义切片信息 [" +
                  m.applyCustomTile +
                  "] 未配置"
                );
              }
            } else {
              initLayer = new TileLayer({
                url: m.url,
                title: m.title,
              });
            }
            break;
          case "feature":
            initLayer = new FeatureLayer({
              url: m.url,
              title: m.title,
            });
            break;
          case "wmts":
            initLayer = new WMTSLayer({
              url: m.url,
              title: m.title,
              customParameters: m.customParameters,
              activeLayer: m.activeLayer,
            });
            break;
          case "web-tile":
            urlTemplate = m.urlTemplate;
            if (TileInfoTMap
            ) {
              initLayer = new WebTileLayer({
                urlTemplate: urlTemplate,
                title: m.title,
                tileInfo: new TileInfo(TileInfoTMap
                ),
                fullExtent: new Extent({
                  xmax: 180,
                  xmin: -180,
                  ymax: 90,
                  ymin: -90,
                  spatialReference: {
                    wkid: 4490,
                  },
                }),
                spatialReference: self.initExtent.spatialReference,
                subDomains: m.subDomains,
              });
            } else {
              console.error(
                "底图 [" +
                m.title +
                "] 所声明自定义切片信息 [" +
                m.applyCustomTile +
                "] 未配置"
              );
            }
            break;
          case "vector-tile":
            initLayer = new VectorTileLayer({
              url: m.url,
              title: m.title,
            });
            break;
          default:
            initLayer = new MapImageLayer({
              url: m.url,
              title: m.title,
            });
            break;
        }
        if (initLayer) {
          if (m.effect) initLayer.effect = m.effect;
          initLayer.minScale = m.minScale ? m.minScale : 0;
          initLayer.maxScale = m.maxScale ? m.maxScale : 0;
          initLayer.isBaseLayer = true;
          initLayer.id = "baseMap_" + index;
          initLayer.class = m.class;
          initLayer.customInitExtent = self.initExtent;
          if (m.class === "影像地图") satelliteBaseLayers.push(initLayer);
          else othersBaseLayers.push(initLayer);
        }
      });
      self.othersBaseMaps = new Basemap({
        baseLayers: othersBaseLayers,
        title: "电子地图",
        id: "OthersBaseMaps",
        thumbnailUrl:
          self.assetsPath + "/assets/img/decorations/othersBaseMaps.png",
      });
      self.satelliteBaseMaps = new Basemap({
        baseLayers: satelliteBaseLayers,
        title: "影像地图",
        id: "SatelliteBaseMaps",
        thumbnailUrl:
          self.assetsPath + "/assets/img/decorations/satelliteBaseMaps.png",
      });
      self.initMap("2d");
    },
    watch: {},
    beforeDestroy() {
      if (this.selectedFeatureHandler) {
        this.selectedFeatureHandler.remove()
      }
      if (this.triggerActionHandler) {
        this.triggerActionHandler.remove()
      }
      if (this.extentWatcher) {
        this.extentWatcher.remove();
      }
      if (this.triggerActionHandler) {
        this.triggerActionHandler.remove();
      }
      if (this.popupVisibleWatcher) {
        this.popupVisibleWatcher.remove();
      }
      if (this.clickHandler) {
        this.clickHandler.remove();
      }
      if (this.moveHandler) {
        this.moveHandler.remove();
      }
      if (this.clipboard) {
        this.clipboard.destroy();
        this.clipboard = null;
      }
    },
  };
  </script>
  
  <style scoped>
  .attributes_table_header {
    color: black;
    height: 36px;
    line-height: 36px;
    text-align: center;
    width: 100%;
    font-size: 16px;
    padding-left: 16px;
    background: rgba(45, 139, 255, 0.3);
  }
  
  .grid_buttons {
    line-height: 32px;
    height: 32px;
    text-align: center;
    cursor: pointer;
    width: fit-content;
    display: inline-block;
    border: 1px solid black;
    border-radius: 4px;
    transition: all 0.4s ease-in-out;
    margin: 0 4px;
    padding: 0 8px;
  }
  
  .grid_buttons:hover {
    background: rgb(45, 140, 255);
    filter: drop-shadow(rgba(0, 0, 0, 0.6) 0.2rem 0.2rem 0.4rem);
  }
  
  .mapPanel {
    position: absolute;
    z-index: 10;
    left: 26vw;
    top: 35vh;
    width: 40vw;
    height: fit-content;
    padding: 16px 8px;
    background: rgb(240, 240, 240);
    box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.6);
    border-radius: 4px;
  }
  
  .mapPanelItem {
    cursor: pointer;
    width: 96%;
    /* display: inline-flex; */
    /* height: 36px;
    line-height: 36px; */
    margin: 0 2%;
    text-align: left;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    border-bottom: 1px solid rgba(100, 100, 100, 0.4);
  }
  
  .mapPanelItem:hover {
    background: rgba(200, 200, 200, 0.2);
  }
  
  .mapPanelItem_table {
    font-size: 14px;
    width: 100%;
  }
  
  .mapPanelItem_table tr {
    line-height: 24px;
  }
  
  .mapPanelItem_table th {
    color: rgb(50, 50, 50);
    font-size: 14px;
  }
  
  .mapPanelItem_table td {
    text-align: right;
    font-size: 14px;
  }
  
  .mapPanelItem span {
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .map_container {
    position: absolute;
    z-index: 1;
    width: 100vw;
    height: 100vh;
    /* background: url("../../assets/img/content/mainBackground2.png") no-repeat; */
    background-size: 100% 100%;
    overflow: hidden;
  }
  
  #scaleBarDiv {
    position: absolute;
    z-index: 1;
    background-color: transparent;
    left: 16px;
    padding: 10px;
  }
  
  .esri-basemap-toggle {
    left: 32px;
    bottom: 64px;
  }
.pickFWKJMButtons_flash {
  animation: glowing 4000ms infinite;
}
  
  @import "https://nfzjszlb.jst.zj.gov.cn/tyzcpt/esriAssets/esriAssets/esri/themes/light/main.css";
  /* @import "./esriUI_rewrite.css"; */
  
  
@keyframes glowing {
  0% {
    background-color: #0482c1;
    box-shadow: 0 0 4px #3295fe;
  }

  50% {
    background-color: #01cce7;
    box-shadow: 0 0 20px #00d9ff;
  }

  100% {
    background-color: #0482c1;
    box-shadow: 0 0 4px #3295fe;
  }
}

  </style>